<template>
  <div class="level-container">
    <div class="level-header">
      <button class="back-btn" @click="goBack">← 返回</button>
      <h2 class="level-title">{{ levelData.name }}</h2>
      <div class="progress">{{ currentQuestion + 1 }} / {{ questions.length }}</div>
    </div>

    <div class="level-content">
      <div class="question-area">
        <h3 class="question-text">数一数，一共有多少个苹果？</h3>

        <div class="visual-math">
          <div class="fruit-group">
            <div class="fruit-container">
              <span v-for="i in currentQuestionData.num1" :key="`a-${i}`" class="fruit">🍎</span>
            </div>
            <div class="number-label">{{ currentQuestionData.num1 }}</div>
          </div>

          <div class="operator">+</div>

          <div class="fruit-group">
            <div class="fruit-container">
              <span v-for="i in currentQuestionData.num2" :key="`b-${i}`" class="fruit">🍎</span>
            </div>
            <div class="number-label">{{ currentQuestionData.num2 }}</div>
          </div>

          <div class="operator">=</div>

          <div class="answer-placeholder">?</div>
        </div>

        <div class="options-grid">
          <DraggableItem
            v-for="option in currentQuestionData.options"
            :key="option"
            :item-id="`number-${option}`"
            :item-value="option"
            item-type="number"
          >
            <div class="number-card">{{ option }}</div>
          </DraggableItem>
        </div>
      </div>

      <div class="answer-area">
        <DropZone
          ref="dropZoneRef"
          zone-id="answer"
          :accepted-value="currentQuestionData.answer"
          accepted-type="number"
          :show-result="true"
          @drop="handleDrop"
        >
          <template #placeholder>
            <div class="drop-placeholder">
              <span class="drop-hint">把答案拖到这里</span>
            </div>
          </template>
          <template #content="{ value }">
            <div class="dropped-number">{{ value }}</div>
          </template>
        </DropZone>
      </div>
    </div>

    <!-- 完成弹窗 -->
    <div v-if="showComplete" class="modal-overlay">
      <div class="modal-content complete-modal">
        <h2>🎉 太棒了！</h2>
        <div class="stars-earned">
          <span v-for="i in starsEarned" :key="i" class="star-big">⭐</span>
        </div>
        <p class="complete-message">你获得了 {{ starsEarned }} 颗星星！</p>
        <div class="complete-buttons">
          <button class="btn btn-primary" @click="goToMap">返回地图</button>
          <button v-if="hasNextLevel" class="btn btn-secondary" @click="goToNextLevel">
            下一关
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useGameStore } from '@/stores/game'
import DraggableItem from '@/components/common/DraggableItem.vue'
import DropZone from '@/components/common/DropZone.vue'
import { soundManager } from '@/utils/sound'
import { createStarEffect, createCelebrationEffect, injectAnimationStyles } from '@/utils/animation'

const router = useRouter()
const route = useRoute()
const gameStore = useGameStore()

const levelId = parseInt(route.params.id as string)
const levelData = computed(() => gameStore.levels.find(l => l.id === levelId)!)

const currentQuestion = ref(0)
const correctAnswers = ref(0)
const showComplete = ref(false)
const dropZoneRef = ref<InstanceType<typeof DropZone>>()

// 生成加法题目
function generateQuestion(num1: number, num2: number) {
  const answer = num1 + num2
  const options = [answer]

  // 生成干扰项
  while (options.length < 4) {
    const distractor = answer + Math.floor(Math.random() * 5) - 2
    if (distractor > 0 && distractor <= 10 && !options.includes(distractor)) {
      options.push(distractor)
    }
  }

  return {
    num1,
    num2,
    answer,
    options: shuffleArray(options)
  }
}

// 题目数据
const questions = ref([
  generateQuestion(1, 2),
  generateQuestion(2, 3),
  generateQuestion(3, 2),
  generateQuestion(4, 1),
  generateQuestion(2, 4)
])

const currentQuestionData = computed(() => questions.value[currentQuestion.value])

const starsEarned = computed(() => {
  const accuracy = correctAnswers.value / questions.value.length
  if (accuracy >= 0.9) return 3
  if (accuracy >= 0.7) return 2
  return 1
})

const hasNextLevel = computed(() => {
  const nextLevel = gameStore.levels.find(l => l.id === levelId + 1)
  return nextLevel !== undefined
})

onMounted(() => {
  injectAnimationStyles()
})

function shuffleArray<T>(array: T[]): T[] {
  const newArray = [...array]
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[newArray[i], newArray[j]] = [newArray[j], newArray[i]]
  }
  return newArray
}

function handleDrop(data: { correct: boolean }) {
  if (data.correct) {
    correctAnswers.value++

    const dropZone = dropZoneRef.value?.$el
    if (dropZone) {
      const rect = dropZone.getBoundingClientRect()
      createStarEffect(rect.left + rect.width / 2, rect.top + rect.height / 2)
    }

    setTimeout(() => {
      if (currentQuestion.value < questions.value.length - 1) {
        currentQuestion.value++
        dropZoneRef.value?.reset()
      } else {
        completeLevel()
      }
    }, 1500)
  } else {
    setTimeout(() => {
      dropZoneRef.value?.reset()
    }, 1000)
  }
}

function completeLevel() {
  showComplete.value = true
  gameStore.completeLevel(levelId, starsEarned.value)
  createCelebrationEffect()
  soundManager.playBadge()
}

function goBack() {
  router.push('/')
}

function goToMap() {
  router.push('/')
}

function goToNextLevel() {
  router.push(`/level/${levelId + 1}`)
  currentQuestion.value = 0
  correctAnswers.value = 0
  showComplete.value = false
}
</script>

<style scoped>
.level-container {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 30px 20px;
  box-sizing: border-box;
  margin: 0;
}

.level-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
  padding: 0 20px;
}

.back-btn {
  font-size: 24px;
  padding: 12px 24px;
  background: #fff;
  border: 2px solid #FF9800;
  border-radius: 15px;
  cursor: pointer;
  font-weight: bold;
  color: #FF9800;
  transition: all 0.2s;
}

.back-btn:hover {
  background: #FF9800;
  color: #fff;
}

.level-title {
  font-size: 36px;
  color: #F57C00;
  margin: 0;
}

.progress {
  font-size: 24px;
  font-weight: bold;
  color: #F57C00;
  background: #fff;
  padding: 10px 20px;
  border-radius: 15px;
}

.level-content {
  max-width: 1200px;
  margin: 0 auto;
}

.question-area {
  background: #fff;
  border-radius: 20px;
  padding: 40px;
  margin-bottom: 40px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.question-text {
  font-size: 48px;
  text-align: center;
  color: #333;
  margin: 0 0 40px 0;
}

.visual-math {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 30px;
  margin-bottom: 40px;
  flex-wrap: wrap;
}

.fruit-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.fruit-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  max-width: 200px;
  justify-content: center;
}

.fruit {
  font-size: 48px;
  animation: fruitPop 0.5s ease-out;
}

@keyframes fruitPop {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.number-label {
  font-size: 36px;
  font-weight: bold;
  color: #FF9800;
  background: #FFF3E0;
  padding: 10px 20px;
  border-radius: 10px;
}

.operator {
  font-size: 64px;
  font-weight: bold;
  color: #FF9800;
}

.answer-placeholder {
  font-size: 64px;
  font-weight: bold;
  color: #999;
  width: 100px;
  height: 100px;
  border: 4px dashed #FF9800;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 20px;
  justify-items: center;
}

.number-card {
  width: 120px;
  height: 120px;
  background: linear-gradient(135deg, #FFB74D 0%, #FF9800 100%);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 64px;
  font-weight: bold;
  color: #fff;
  box-shadow: 0 6px 16px rgba(255, 152, 0, 0.4);
}

.answer-area {
  display: flex;
  justify-content: center;
}

.drop-placeholder {
  padding: 40px;
}

.drop-hint {
  font-size: 24px;
  color: #999;
}

.dropped-number {
  font-size: 64px;
  font-weight: bold;
  color: #FF9800;
}

/* 完成弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.complete-modal {
  background: #fff;
  border-radius: 30px;
  padding: 60px;
  text-align: center;
  animation: scaleIn 0.5s;
}

@keyframes scaleIn {
  from {
    transform: scale(0.5);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

.complete-modal h2 {
  font-size: 48px;
  margin: 0 0 30px 0;
  color: #4CAF50;
}

.stars-earned {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 30px;
}

.star-big {
  font-size: 64px;
  animation: starPop 0.5s ease-out;
}

@keyframes starPop {
  0% {
    transform: scale(0) rotate(0deg);
  }
  50% {
    transform: scale(1.2) rotate(180deg);
  }
  100% {
    transform: scale(1) rotate(360deg);
  }
}

.complete-message {
  font-size: 28px;
  color: #333;
  margin-bottom: 40px;
}

.complete-buttons {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.btn {
  padding: 15px 40px;
  font-size: 24px;
  border: none;
  border-radius: 15px;
  cursor: pointer;
  font-weight: bold;
  transition: transform 0.2s;
}

.btn:hover {
  transform: scale(1.05);
}

.btn-primary {
  background: #4CAF50;
  color: #fff;
}

.btn-secondary {
  background: #FF9800;
  color: #fff;
}
</style>
